package com.cht.commonUtil.jenkins;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.jenkins.JenkinsJob.Action;
import com.cht.commonUtil.structure.S2;
import com.cht.commonUtil.enums.MailType;
import com.cht.commonUtil.enums.RecipientType;
import com.cht.commonUtil.enums.Roles;
import com.cht.commonUtil.enums.ToDoType;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class PostAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		/*
		 * 1.	寫入log
		 * 
		 * */
		
		
		String sql = "INSERT INTO buildLog (modId,jobSN,rootJobId,rootJobSN,bDT,eDT,buildResult,chkInId) VALUES (?,?,?,?,?,?,?,?)";
		
		
		String subsysId = request.getParameter("subsysId");
		String modId = request.getParameter("modId");
		String committer = request.getParameter("committer");
		boolean isOL = Boolean.parseBoolean( request.getParameter("isOL") );
		
		String rootJobId = "";
		int rootJobSN = 0;
		int chkInId = Integer.parseInt( request.getParameter("chkInId") );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		
		String json = "";
		try {
			//取得最後執行的job號
			json = Widgets.readUrl( Widgets.getJenkinsUrl(modId, 0, "json") );
			int jobSN = new Gson().fromJson(json, JenkinsJobFull.class ).getLastBuild().getNumber();	//取得目前的jobSN
			
			json = Widgets.readUrl( Widgets.getJenkinsUrl(modId,jobSN,"json") );
			JenkinsJob jobStatus = new Gson().fromJson(json, JenkinsJob.class );
			for( Action act : jobStatus.getActions() ) {
				if( act.getCauses() != null && act.getCauses().size() != 0 ) {
					String shortDescription = act.getCauses().get(0).getShortDescription();
					rootJobId = shortDescription.substring("Started by build flow ".length(), shortDescription.lastIndexOf("#") );
					rootJobSN = Integer.parseInt( shortDescription.substring( shortDescription.lastIndexOf("#")+1,shortDescription.length()) );
				}
			}
			
			String result = jobStatus.getResult();	//取得這個job的執行結果
			
			Timestamp cDT = Widgets.cDT();			//目前的Timestamp
			
			//加入持續時間，以得結束時間
			Calendar cal = Calendar.getInstance();	
	        cal.setTimeInMillis( cDT.getTime() );
	        cal.add(Calendar.MILLISECOND, jobStatus.getDuration() );
	        Timestamp eDT = new Timestamp(cal.getTime().getTime());
			
			conn = Widgets.getConn();
			
			//寫入執行記錄
			ps = conn.prepareStatement(sql);
			ps.setString(1, modId);
			ps.setInt(2, jobSN);
			ps.setString(3, rootJobId);
			ps.setInt(4, rootJobSN);
			ps.setTimestamp(5, cDT );
			ps.setTimestamp(6, eDT );
			ps.setString(7, result);
			ps.setInt(8, chkInId);
			ps.execute();
			if ( ps !=null ) {ps.close();}
			
			if( "SUCCESS".equalsIgnoreCase(result) ) {	//執行成功
				/*
				 * 1.	此檔有無在部署檔清單中
				 * 2.	簽入SVN CM 執行檔
				 * 3.	寫入版次對應
				 * 4.	是否為最後一個檔案
				 * 5.	寄發通知信
				 * 6.	寫入測試人員待辦事項
				 * */
				
				sql = "SELECT modId,isFinal FROM objectList WHERE subsysId=? AND modId IN (?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, modId+".war");
				ps.setString(3, modId+".ear");
				ps.setString(4, modId+".jar");
				System.out.println("現在在判斷那個模組："+modId);
				rs = ps.executeQuery();
				if( rs.next() ) {	//有存在
					
					boolean isFinal = "t".equalsIgnoreCase( rs.getString("isFinal") );
					//最後一個檔案簽入時，再調整count值
					
					String[] svnLoginInfo = Widgets.getEXEsvnLoginInfo(subsysId,isOL,isFinal);
					
					System.out.println();
					
					String exeFile = rs.getString("modId");
					System.out.println(exeFile+"有在部署清單");
					if ( rs !=null ) {rs.close();}
					if ( ps !=null ) {ps.close();}
					
					if( isFinal ) {
						
						List<S2> modFolderOnOS = new ArrayList<S2>();
						sql = "SELECT modId FROM objectlist WHERE subsysId=?";
						ps = conn.prepareStatement(sql);
						ps.setString(1, subsysId);
						rs = ps.executeQuery();
						while ( rs.next() ) {
							S2 s2 = new S2();
							s2.setS1( rs.getString(1) );	//檔名
							System.out.println( s2.getS1() );
							if ( isOL ) {
								s2.setS2( "OL_"+(s2.getS1().split("\\."))[0] );	//資料夾名
							} else {
								s2.setS2( "MR_"+(s2.getS1().split("\\."))[0] );	//資料夾名
							}
							modFolderOnOS.add( s2 );
						}
						
						//得到簽入的版次，並記錄到繳交的table中
						long revision = Widgets.checkInFiles2SVN(svnLoginInfo[0], svnLoginInfo[1], svnLoginInfo[2], "", modFolderOnOS);
				        System.out.println("簽入的版次是"+revision);
						sql = "UPDATE chkinmain SET exeVer=?,svnExeRepoSN=? WHERE chkInMainId=?";
						ps = conn.prepareStatement(sql);
						ps.setLong(1, revision);
						ps.setInt(2, Integer.parseInt( svnLoginInfo[4] ) );
						ps.setInt(3, chkInId);
						ps.executeUpdate();
						
						//最後一個，驅動 "測試人員安排部署時間"
						Widgets.genToDoList(subsysId, String.valueOf(chkInId), committer, ToDoType.WAITING2DEPLOY, Roles.TESTER);
						
						System.out.println("最後一個");
						
						//寄發通知信 予測試人員 供其進行部署
						sql = "SELECT subsysDesc FROM subsyses WHERE subsysId=?";
						ps = conn.prepareStatement(sql);
						ps.setString(1,subsysId);
						rs = ps.executeQuery();
						rs.next();
						String subsysDesc = rs.getString(1);
						
						String reqs = "<ul class='zhTwN req'>";
						sql = "SELECT t1.reqSID,t1.reqDesc FROM reqs t1,mpChkinReq t2 WHERE t1.reqId=t2.reqId AND t2.chkInMainId=?";
						ps = conn.prepareStatement(sql);
						ps.setInt(1, chkInId);
						rs = ps.executeQuery();
						while( rs.next() ) {
							reqs += "<li>"+rs.getString("reqSID")+"-"+rs.getString("reqDesc")+"</li>";
						}
						reqs += "</ul>";
						String msgBody = "<font face='微軟正黑體'>您好,<p>目前有一部署工作等待您指派部署與進行測試， 其需求如下。<p> ";	//信件內容
						msgBody += "相關需求："+reqs+"<p><p>Best regards<br></font><p><p>";
						
						List<String[]> tos = Widgets.getRecipient(MailType.WAIT2DEPLOY, RecipientType.TO, subsysId);
						List<String[]> ccs = Widgets.getRecipient(MailType.WAIT2DEPLOY, RecipientType.CC, subsysId);
						List<String[]> bccs = Widgets.getRecipient(MailType.WAIT2DEPLOY, RecipientType.BCC, subsysId);
						String subject = subsysDesc+"-等待部署-"+chkInId;
						Widgets.sendMailMain(tos,ccs,bccs,subject, msgBody);	
					}
				}
			}
		} catch( Exception e ) {
			e.printStackTrace();
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write(json);
	}
}

